#!/bin/zsh
set -u

export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

SCRIPT_DIR=${0:A:h}
CONTENTS_DIR=${SCRIPT_DIR:h}
CLIENT_DIR="$CONTENTS_DIR/Resources/client"
CLIENT_BIN="$CLIENT_DIR/otclient_mac"
APP_TITLE="Mist of Death"

show_dialog() {
  local message="$1"
  MOD_MESSAGE="$message" MOD_TITLE="$APP_TITLE" /usr/bin/osascript <<'APPLESCRIPT'
display dialog (system attribute "MOD_MESSAGE") with title (system attribute "MOD_TITLE") buttons {"OK"} default button "OK"
APPLESCRIPT
}

prompt_xquartz_install() {
  local response
  response=$(MOD_TITLE="$APP_TITLE" /usr/bin/osascript <<'APPLESCRIPT'
set promptText to "Mist of Death for Mac needs XQuartz the first time you launch it. Install XQuartz, log out and back in once, then reopen this app."
set dialogResult to display dialog promptText with title (system attribute "MOD_TITLE") buttons {"Cancel", "Open XQuartz Download"} default button "Open XQuartz Download"
return button returned of dialogResult
APPLESCRIPT
)

  if [[ "$response" == "Open XQuartz Download" ]]; then
    /usr/bin/open "https://www.xquartz.org/"
  fi
}

if [[ ! -f "$CLIENT_BIN" ]]; then
  show_dialog "The bundled client files are missing. Re-download the Mac starter pack and unzip it again before launching."
  exit 1
fi

/bin/chmod +x "$CLIENT_BIN" >/dev/null 2>&1 || true

if ! /usr/bin/open -Ra "XQuartz"; then
  prompt_xquartz_install
  exit 1
fi

/bin/mkdir -p /tmp/.X11-unix >/dev/null 2>&1 || true
/bin/chmod 1777 /tmp/.X11-unix >/dev/null 2>&1 || true

/usr/bin/open -a "XQuartz"

typeset -i attempts=0
until [[ -S /tmp/.X11-unix/X0 || $attempts -ge 20 ]]; do
  /bin/sleep 1
  attempts=$((attempts + 1))
done

if [[ ! -S /tmp/.X11-unix/X0 ]]; then
  show_dialog "XQuartz did not finish starting. If you just installed it, log out and back in once, then try opening Mist of Death again."
  exit 1
fi

export DISPLAY=:0
export XAUTHORITY="$HOME/.Xauthority"

cd "$CLIENT_DIR" || exit 1
"$CLIENT_BIN"
status=$?

if [[ $status -ne 0 ]]; then
  show_dialog "Mist of Death closed before it finished starting. If this was your first launch, install XQuartz, log out and back in once, and try again. The raw fallback instructions are on the Mac Guide page."
fi

exit $status
